import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref({
    id: '',
    username: '',
    avatar: '',
    email: ''
  })
  
  // 登录状态
  const isLogin = ref(false)
  
  // 登录弹窗显示状态
  const showLoginModal = ref(false)
  
  // 设置用户信息
  function setUserInfo(info: any) {
    userInfo.value = info
    isLogin.value = true
    localStorage.setItem('token', info.token || '')
    localStorage.setItem('userInfo', JSON.stringify(info))
  }
  
  // 清除用户信息
  function clearUserInfo() {
    userInfo.value = {
      id: '',
      username: '',
      avatar: '',
      email: ''
    }
    isLogin.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }
  
  // 显示登录弹窗
  function toggleLoginModal(show: boolean) {
    showLoginModal.value = show
  }
  
  // 检查登录状态
  function checkLogin() {
    const token = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (token && storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo)
      isLogin.value = true
      return true
    }
    
    return false
  }
  
  return {
    userInfo,
    isLogin,
    showLoginModal,
    setUserInfo,
    clearUserInfo,
    toggleLoginModal,
    checkLogin
  }
}) 